import React from 'react'
import { Form, Input, Button, Checkbox, message } from 'antd'
import { Link } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import './index.scss'
import { loginAsyncAction } from '../../store/userStore/action'

const Login = (props) => {
  const dispatch = useDispatch()
  const [form] = Form.useForm()

  const onFinish = (values) => {
    console.log('Received values of form: ', values);
    dispatch(loginAsyncAction({
      username: values.username,
      password: values.password
    }))
      .then(res => {
        console.log('登陆成功：', res)
        message.success('登陆成功')
        props.history.push('/home')
      })
      .catch(err => {
        console.log('登陆失败：', err)
        message.error(err.errMsg)
        form.resetFields() // 重置
      })
  }

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  }

  return (
    <Form
      form={form}
      id="login-form"
      name="normal_login"
      className="login-form"
      initialValues={{
        remember: true,
      }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
    >
      <Form.Item
        name="username"
        rules={[
          {
            required: true,
            message: '请输入你的用户名!',
          },
        ]}
      >
        <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="请输入账号" />
      </Form.Item>
      <Form.Item
        name="password"
        rules={[
          {
            required: true,
            message: '请输入你得密码!',
          },
        ]}
      >
        <Input
          prefix={<LockOutlined className="site-form-item-icon" />}
          type="password"
          placeholder="请输入密码"
        />
      </Form.Item>

      <Form.Item className='input-forget'>
        <Form.Item name="remember" valuePropName="checked" noStyle>
          <Checkbox>记住密码</Checkbox>
        </Form.Item>

        <Link className="login-form-forgot" to="">
          忘记密码
        </Link>
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit" className="login-form-button">
          登录
        </Button>
      </Form.Item>
    </Form>
  );
}

export default Login